<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属站点" prop="stationIdC">
        <el-select v-model="queryParams.stationIdC" @change="stationOptionChange" placeholder="请选择站点" clearable filterable>
          <el-option
            v-for="item in stationOptions"
            :key="item.stationIdC"
            :label="item.stationName + ',' + item.stationIdC"
            :value="item.stationIdC">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="历史设备" prop="equipHistoryId">
        <el-select v-model="queryParams.equipHistoryId" placeholder="请选择历史设备" clearable filterable>
          <el-option
            v-for="item in equipHistoryOptions"
            :key="item.equipHistoryId"
            :label="item.equipName"
            :value="item.equipHistoryId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维护编号" prop="serviceCode">
        <el-input
          v-model="queryParams.serviceCode"
          placeholder="请输入维护单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="serviceStartTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.serviceStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择维护开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="serviceEndTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.serviceEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择维护结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="维护类型" prop="serviceTypeId">
        <el-select v-model="queryParams.serviceTypeId" placeholder="请选择维护类型" clearable size="small">
          <el-option
            v-for="item in serviceTypeOptions"
            :key="item.serviceTypeId"
            :label="item.serviceTypeName"
            :value="item.serviceTypeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维护状态" prop="serviceState">
        <el-select v-model="queryParams.serviceState" placeholder="请选择维护单状态" clearable size="small">
          <el-option
            v-for="dict in serviceStateOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['modules:serviceInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['modules:serviceInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['modules:serviceInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['modules:serviceInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serviceInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维护ID" align="center" prop="serviceId" v-if="false"/>
      <el-table-column label="所属站点" align="center" prop="stationIdC">
        <template slot-scope="scope">
          <span>{{ stationName(scope.row.stationIdC) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点历史设备" align="center" prop="equipHistoryId" >
        <template slot-scope="scope">
          <span>{{ equipHistoryName(scope.row.equipHistoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护单编号" align="center" prop="serviceCode" />
      <el-table-column label="维护开始时间" align="center" prop="serviceStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.serviceStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护结束时间" align="center" prop="serviceEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.serviceEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护人" align="center" prop="servicePeopleName" />
      <el-table-column label="维护结果" align="center" prop="serviceResult" />
      <el-table-column label="维护类型" align="center" prop="serviceTypeId" >
        <template slot-scope="scope">
          <span>{{ serviceTypeName(scope.row.serviceTypeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护单状态" align="center" prop="serviceState" >
        <template slot-scope="scope">
          {{ serviceStateName(scope.row.serviceState) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['modules:serviceInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['modules:serviceInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维护单管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body style="padding: 0 20px">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-form-item label="维护编号" prop="serviceCode">
                <el-input v-model="form.serviceCode" placeholder="请输入维护单编号" disabled/>
              </el-form-item>
              <el-col :span="12">
                <el-form-item label="所属站点" prop="stationId">
                  <el-select v-model="form.stationId" placeholder="请选择站点" @change="stationOptionChange" clearable filterable>
                    <el-option
                      v-for="item in stationOptions"
                      :key="item.stationId"
                      :label="item.stationName + ',' + item.stationIdC"
                      :value="item.stationId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="历史设备" prop="equipHistoryId">
                  <el-select v-model="form.equipHistoryId" placeholder="请选择历史设备" clearable filterable>
                    <el-option
                      v-for="item in equipHistoryOptions"
                      :key="item.equipHistoryId"
                      :label="item.equipName"
                      :value="item.equipHistoryId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="开始时间" prop="serviceStartTime">
                  <el-date-picker clearable size="small"
                                  v-model="form.serviceStartTime"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss"
                                  placeholder="选择维护开始时间"
                                  style="width: 200px">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="serviceEndTime">
                  <el-date-picker clearable size="small"
                                  v-model="form.serviceEndTime"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss"
                                  placeholder="选择维护结束时间"
                                  style="width: 200px">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="维护结果" prop="serviceResult">
                  <el-input v-model="form.serviceResult" placeholder="请输入维护结果" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="现场照片">
                  <el-upload
                    name="files"
                    ref="uploadSitePhoto"
                    :action="uploadPhotoUrl()"
                    :file-list="sitePhotoUrlList"
                    :auto-upload="true"
                    :before-upload="beforeUploadPhoto"
                    :on-remove="removeSitePhoto"
                    accept="image/jpg,image/jpeg,image/png"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <template #tip>
                      <div class="el-upload__tip">
                        只能上传 jpg/jpeg/png 文件，且不超过 500kb
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="维护人" prop="servicePeopleName">
                  <el-input v-model="form.servicePeopleName" placeholder="请输入维护人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="servicePeoplePhone">
                  <el-input v-model="form.servicePeoplePhone" placeholder="请输入维护人联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="维护类型" prop="serviceTypeId">
                  <el-select v-model="form.serviceTypeId" placeholder="请选择维护类型ID">
                    <el-option
                      v-for="item in serviceTypeOptions"
                      :key="item.serviceTypeId"
                      :label="item.serviceTypeName"
                      :value="item.serviceTypeId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="serviceState">
                  <el-select v-model="form.serviceState" placeholder="请选择维护单状态">
                    <el-option
                      v-for="dict in serviceStateOptions"
                      :key="dict.key"
                      :label="dict.value"
                      :value="dict.key"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="22">
                <el-form-item label="备注">
                  <editor v-model="form.remark" :min-height="192"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: center">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
  </div>
</template>

<script>
import { listServiceInfo, getServiceInfo, delServiceInfo, addServiceInfo, updateServiceInfo, exportServiceInfo, getServiceCode } from "@/api/modules/serviceInfo";
import {listInfoByDto} from "@/api/modules/info";
import { listStationEquipHistoryOption }  from "@/api/modules/equipHistory";
import { listServiceType } from "@/api/modules/serviceType";
import Editor from '@/components/Editor';
import { uploadByParent } from "@/api/modules/upload";
import { listIdAndNickName } from "@/api/system/user";

export default {
  name: "ServiceInfo",
  components: {
    Editor
  },
  data() {
    return {
      deletePhotoList:[],
      // 现场照片集合
      sitePhotoUrlList: [],
      // 维护状态
      serviceStateOptions:[
        {"key":1,value:'未接单'},
        {"key":2,value:'处理中'},
        {"key":3,value:'提交结果'},
        {"key":4,value:'处理完成'}
      ],
      // 所有用户选择
      allUserOptions:[],
      // 站点设备选择
      equipHistoryOptions:[],
      // 维修类型选择列表
      serviceTypeOptions:[],
      // 站点选择列表
      stationOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维护单管理表格数据
      serviceInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationIdC: undefined,
        equipHistoryId: undefined,
        serviceCode: undefined,
        serviceStartTime: undefined,
        serviceEndTime: undefined,
        serviceTypeId: undefined,
        serviceState: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    /** 获取维修单编号 */
    initServiceCode(){
      getServiceCode().then(res=>{
        this.form.serviceCode = res.data.serviceCode
      });
    },
    /** 图片移除 */
    removeSitePhoto(file, fileList){
      // 记录删除的照片
      this.deletePhotoList.push(file);
      // 移除
      this.sitePhotoUrlList = fileList
    },
    /** 上传照片前的操作 */
    beforeUploadPhoto(files){
      let formData = new FormData();
      formData.append("files",files);
      uploadByParent(formData,"service").then(res=>{
        let resList = res.data;
        if(resList){
          this.sitePhotoUrlList = this.sitePhotoUrlList.concat(resList);
        }
      })
    },
    /** 上传照片路径 */
    uploadPhotoUrl(){
      return process.env.VUE_APP_BASE_API + "/uploadByPatent?parent=service"
    },
    /** 根据站点ID查询历史设备 */
    equipHistoryByStationIdC(stationIdC){
      let selectDto = {
        stationIdC:stationIdC
      };
      listStationEquipHistoryOption(selectDto).then(res=>{
        this.equipHistoryOptions = res.data;
      })
    },
    /** 站点下拉框发生变化时 */
    stationOptionChange(stationIdC){
      // 历史设备发生变化
      this.equipHistoryByStationIdC(stationIdC);
      this.form.equipHistoryId = '';
    },
    /** 初始化 */
    init(){
      let selectDto = {
        stationState:1
      };
      let serviceType = {
        serviceTypeState:0
      }
      listInfoByDto(selectDto).then(res=>{
        this.stationOptions = res.data;
      });
      listServiceType(serviceType).then((res=>{
        this.serviceTypeOptions = res.rows;
      }))
      listStationEquipHistoryOption().then(res=>{
        this.allEquipHistory = res.data;
        this.equipHistoryOptions = res.data;
      })
      listIdAndNickName().then(res=>{
        this.allUserOptions = res;
      })
    },
    /** 回显维护类型名称 */
    serviceTypeName(serviceTypeId){
      let value = '';
      this.serviceTypeOptions.forEach(serviceType =>{
        if(serviceType.serviceTypeId === serviceTypeId){
          value = serviceType.serviceTypeName;
        }
      });
      return value;
    },
    /** 回显历史设备名称 */
    equipHistoryName(equipHistoryId){
      let value = '';
      this.allEquipHistory.forEach(equipHistory =>{
        if(equipHistory.equipHistoryId === equipHistoryId){
          value = equipHistory.equipName;
          return value;
        }
      });
      return value;
    },
    /** 回显站点名称 */
    stationName(stationIdC){
      let value = '';
      this.stationOptions.forEach(station =>{
        if(station.stationIdC === stationIdC){
          value = station.stationName + "," + station.stationIdC;
          return value;
        }
      });
      return value;
    },
    /** 回显维护状态 */
    serviceStateName(key){
      let value = '';
      this.serviceStateOptions.forEach(service =>{
        if(service.key === key){
          value = service.value;
        }
      });
      return value;
    },
    /** 查询维护单管理列表 */
    getList() {
      this.loading = true;
      listServiceInfo(this.queryParams).then(response => {
        this.serviceInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.sitePhotoUrlList = [];
      this.deletePhotoList = [];
      this.form = {
        serviceId: undefined,
        stationIdC: undefined,
        equipHistoryId: undefined,
        serviceCode: undefined,
        serviceStartTime: undefined,
        serviceEndTime: undefined,
        serviceUserId: undefined,
        serviceResult: undefined,
        serviceTypeId: undefined,
        serviceState: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.serviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 初始化维护单编号
      this.initServiceCode();
      this.open = true;
      this.title = "添加维护单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const serviceId = row.serviceId || this.ids
      getServiceInfo(serviceId).then(response => {
        this.sitePhotoUrlList = response.data.tbaseServicePhotoList;
        this.form = response.data;
        this.open = true;
        this.title = "修改维护单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.sitePhotoUrlList = this.sitePhotoUrlList;
        this.form.deletePhotoList = this.deletePhotoList;
        if (valid) {
          if (this.form.serviceId != null) {
            updateServiceInfo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addServiceInfo(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const serviceIds = row.serviceId || this.ids;
      this.$confirm('是否确认删除维护单管理编号为"' + serviceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delServiceInfo(serviceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有维护单管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportServiceInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
